/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

package com.mcgrobot.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.mcgrobot.common.Constants;
import com.mcgrobot.entity.auth.McgUser;
import com.mcgrobot.entity.auth.PermissionCollection;
import com.mcgrobot.entity.auth.UserCacheBean;
import com.mcgrobot.plugin.endesign.RSAEncrypt;
import com.mcgrobot.service.DbService;
import com.mcgrobot.service.UserService;
import com.mcgrobot.util.Tools;

@Service
public class UserServiceImpl implements UserService {

	private static final Logger logger = LoggerFactory.getLogger(STimetaskServiceImpl.class);
	
    @Autowired
    private DbService dbService;
	
	@Override
	public McgUser selectByPrimaryKey(String account) throws ClassNotFoundException, IOException {
		McgUser mcgUser = dbService.query(Tools.buildMcgUserKey(account), McgUser.class);
		return mcgUser;
	}

	@Override
	public List<McgUser> getUserList() throws ClassNotFoundException, IOException {
		ConcurrentHashMap<String, String> mcgUserMap = dbService.query(Constants.MCG_USER_KEY, ConcurrentHashMap.class);
		if(mcgUserMap == null) {
			return null;
		}
		List<McgUser> mcgUserList = new ArrayList<>();
		if(mcgUserMap.size() > 0) {
			for(String account : mcgUserMap.values()) {
				McgUser mcgUser = dbService.query(Tools.buildMcgUserKey(account), McgUser.class);
				if(mcgUser != null) {
					mcgUserList.add(mcgUser);
				}
			}
		}
		return mcgUserList;
	}

	@Override
	public int insertSelective(McgUser mcgUser) {
		int flag = 0;
		try {
			ConcurrentHashMap<String, String> mcgUserMap = dbService.query(Constants.MCG_USER_KEY, ConcurrentHashMap.class);
			if(mcgUserMap == null) {
				mcgUserMap = new ConcurrentHashMap<>();
			}
			if(mcgUserMap.get(mcgUser.getAccount()) == null) {
				mcgUserMap.put(mcgUser.getAccount(), mcgUser.getAccount());
				dbService.save(Constants.MCG_USER_KEY, mcgUserMap);
				mcgUser.setUserId(UUID.randomUUID().toString());
				mcgUser.setCreateTime(new Date());
				mcgUser.setPwd(DigestUtils.md5DigestAsHex(RSAEncrypt.segmentDecrypt(mcgUser.getPwd()).getBytes(Constants.CHARSET)));
				UserCacheBean ucb = PermissionCollection.getInstance().getLoginUser();
				mcgUser.setCreateUser(ucb.getUser().getUserName());
				dbService.save(Tools.buildMcgUserKey(mcgUser.getAccount()), mcgUser);
				flag = 1;
			}
			
		} catch (Exception e) {
			logger.error("创建用户失败：", e);
		}
		return flag;
	}

	@Override
	public int deleteByPrimaryKey(String account) {
		int flag = 0;
		try {
			ConcurrentHashMap<String, String> mcgUserMap = dbService.query(Constants.MCG_USER_KEY, ConcurrentHashMap.class);
			if(mcgUserMap != null && mcgUserMap.get(account) != null) {
				mcgUserMap.remove(account);
				dbService.save(Constants.MCG_USER_KEY, mcgUserMap);
				dbService.delete(Tools.buildMcgUserKey(account));
			}
			flag = 1;
		} catch (Exception e) {
			logger.error("删除用户失败：", e);
		}
		return flag;
	}

	@Override
	public int updateByPrimaryKeySelective(McgUser mcgUser) {
		int flag = 0;
		try {
			McgUser lastMcgUser = dbService.query(Tools.buildMcgUserKey(mcgUser.getAccount()), McgUser.class);
			if(lastMcgUser != null) {
				lastMcgUser.setUserName(mcgUser.getUserName());
				lastMcgUser.setPwd(mcgUser.getPwd());
				lastMcgUser.setRoleType(mcgUser.getRoleType());
				lastMcgUser.setSex(mcgUser.getSex());
				lastMcgUser.setStatus(mcgUser.getStatus());
				lastMcgUser.setPhone(mcgUser.getPhone());
				lastMcgUser.setEmail(mcgUser.getEmail());
				lastMcgUser.setUpdateTime(new Date());
				UserCacheBean ucb = PermissionCollection.getInstance().getLoginUser();
				lastMcgUser.setUpdateUser(ucb.getUser().getUserName());
				
				dbService.save(Tools.buildMcgUserKey(mcgUser.getAccount()), lastMcgUser);
				flag = 1;
			}
		} catch (Exception e) {
			logger.error("修改用户失败：", e);
		}
		return flag;
	}

}
